package org.chen.newsapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Getter;
import lombok.Setter;
import org.chen.newsapi.common.Result;
import org.chen.newsapi.entity.Article;
import org.chen.newsapi.entity.Tag;
import org.chen.newsapi.entity.Category;
import org.chen.newsapi.mapper.ArticleMapper;
import org.chen.newsapi.mapper.TagMapper;
import org.chen.newsapi.mapper.CategoryMapper;
import org.chen.newsapi.util.HtmlContentProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/apis/admin")
public class AdminController {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private HtmlContentProcessor htmlContentProcessor;

        /**
         * 获取文章列表（管理后台）
         */
        @GetMapping("/articles")
        public Result<IPage<Article>> getArticles(
                @RequestParam(defaultValue = "1") Integer page,
                @RequestParam(defaultValue = "10") Integer size,
                @RequestParam(required = false) String keyword,
                @RequestParam(required = false) String category,
                @RequestParam(required = false) Integer status) {

            Page<Article> pageParam = new Page<>(page, size);
            LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();

            // 关键词搜索
            if (keyword != null && !keyword.trim().isEmpty()) {
                wrapper.and(w -> w.like(Article::getTitle, keyword)
                        .or().like(Article::getSummary, keyword)
                        .or().like(Article::getAuthor, keyword));
            }

            // 分类筛选
            if (category != null && !category.trim().isEmpty()) {
                wrapper.eq(Article::getCategory, category);
            }

            // 状态筛选
            if (status != null) {
                wrapper.eq(Article::getStatus, status);
            }

            wrapper.orderByDesc(Article::getCreateTime);

            IPage<Article> result = articleMapper.selectPage(pageParam, wrapper);
            return Result.success(result);
        }

        /**
         * 获取文章详情
         */
        @GetMapping("/articles/{id}")
        public Result<Article> getArticle(@PathVariable String id) {
            Article article = articleMapper.selectById(id);
            if (article == null) {
                return Result.error("文章不存在");
            }
            return Result.success(article);
        }

        /**
         * 新增文章
         */
        @PostMapping("/articles")
        public Result<String> createArticle(@RequestBody Article article) {
            try {
                // 验证HTML内容安全性
                if (!htmlContentProcessor.isContentSafe(article.getContentHtml())) {
                    return Result.error("文章内容包含不安全的HTML标签");
                }

                // 处理HTML内容
                if (article.getContentHtml() != null && !article.getContentHtml().trim().isEmpty()) {
                    article.setContentHtml(htmlContentProcessor.processHtmlContent(article.getContentHtml()));
                }

                // 如果没有摘要，自动生成
                if (article.getSummary() == null || article.getSummary().trim().isEmpty()) {
                    article.setSummary(htmlContentProcessor.generateSummary(article.getContentHtml(), 200));
                }

                article.setCreateTime(LocalDateTime.now());
                article.setUpdateTime(LocalDateTime.now());
                article.setViewCount(0L);
                if (article.getStatus() == null) {
                    article.setStatus(0); // 默认草稿状态
                }

                articleMapper.insert(article);
                return Result.success("文章创建成功");
            } catch (Exception e) {
                return Result.error("创建失败：" + e.getMessage());
            }
        }

        /**
         * 更新文章
         */
        @PutMapping("/articles/{id}")
        public Result<String> updateArticle(@PathVariable String id, @RequestBody Article article) {
            try {
                // 验证HTML内容安全性
                if (!htmlContentProcessor.isContentSafe(article.getContentHtml())) {
                    return Result.error("文章内容包含不安全的HTML标签");
                }

                // 处理HTML内容
                if (article.getContentHtml() != null && !article.getContentHtml().trim().isEmpty()) {
                    article.setContentHtml(htmlContentProcessor.processHtmlContent(article.getContentHtml()));
                }

                // 如果没有摘要，自动生成
                if (article.getSummary() == null || article.getSummary().trim().isEmpty()) {
                    article.setSummary(htmlContentProcessor.generateSummary(article.getContentHtml(), 200));
                }

                article.setId(id);
                article.setUpdateTime(LocalDateTime.now());
                articleMapper.updateById(article);
                return Result.success("文章更新成功");
            } catch (Exception e) {
                return Result.error("更新失败：" + e.getMessage());
            }
        }

        /**
         * 删除文章
         */
        @DeleteMapping("/articles/{id}")
        public Result<String> deleteArticle(@PathVariable String id) {
            try {
                articleMapper.deleteById(id);
                return Result.success("文章删除成功");
            } catch (Exception e) {
                return Result.error("删除失败：" + e.getMessage());
            }
        }

        /**
         * 批量设置文章权重
         */
        @PostMapping("/articles/weight")
        public Result<String> setArticleWeight(@RequestBody WeightRequest request) {
            try {
                Article article = articleMapper.selectById(request.getArticleId());
                if (article == null) {
                    return Result.error("文章不存在");
                }

                // 重置所有权重
                article.setIsTop(false);
                article.setIsHot(false);
                article.setIsRecommend(false);
                article.setTopOrder(null);
                article.setHotOrder(null);
                article.setRecommendOrder(null);

                // 设置指定权重
                if ("top".equals(request.getWeightType())) {
                    article.setIsTop(true);
                    article.setTopOrder(request.getOrderValue());
                } else if ("hot".equals(request.getWeightType())) {
                    article.setIsHot(true);
                    article.setHotOrder(request.getOrderValue());
                } else if ("recommend".equals(request.getWeightType())) {
                    article.setIsRecommend(true);
                    article.setRecommendOrder(request.getOrderValue());
                }

                articleMapper.updateById(article);
                return Result.success("权重设置成功");
            } catch (Exception e) {
                return Result.error("设置失败：" + e.getMessage());
            }
        }

        /**
         * 获取所有分类
         */
        @GetMapping("/categories")
        public Result<List<Category>> getCategories() {
            try {
                List<Category> categories = categoryMapper.selectList(
                        new LambdaQueryWrapper<Category>()
                                .orderByAsc(Category::getSortOrder)
                                .orderByDesc(Category::getCreateTime)
                );
                return Result.success(categories);
            } catch (Exception e) {
                return Result.error("获取分类失败：" + e.getMessage());
            }
        }

        /**
         * 获取分类详情
         */
        @GetMapping("/categories/{id}")
        public Result<Category> getCategory(@PathVariable Long id) {
            try {
                Category category = categoryMapper.selectById(id);
                if (category == null) {
                    return Result.error("分类不存在");
                }
                return Result.success(category);
            } catch (Exception e) {
                return Result.error("获取分类失败：" + e.getMessage());
            }
        }

        /**
         * 创建分类
         */
        @PostMapping("/categories")
        public Result<String> createCategory(@RequestBody Category category) {
            try {
                // 检查分类名称是否已存在
                LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Category::getName, category.getName());
                if (categoryMapper.selectCount(wrapper) > 0) {
                    return Result.error("分类名称已存在");
                }

                category.setCreateTime(LocalDateTime.now());
                category.setUpdateTime(LocalDateTime.now());
                if (category.getIsActive() == null) {
                    category.setIsActive(true);
                }
                if (category.getSortOrder() == null) {
                    category.setSortOrder(0);
                }

                categoryMapper.insert(category);
                return Result.success("分类创建成功");
            } catch (Exception e) {
                return Result.error("创建失败：" + e.getMessage());
            }
        }

        /**
         * 更新分类
         */
        @PutMapping("/categories/{id}")
        public Result<String> updateCategory(@PathVariable Long id, @RequestBody Category category) {
            try {
                // 检查分类是否存在
                Category existingCategory = categoryMapper.selectById(id);
                if (existingCategory == null) {
                    return Result.error("分类不存在");
                }

                // 检查分类名称是否已被其他分类使用
                LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Category::getName, category.getName())
                        .ne(Category::getId, id);
                if (categoryMapper.selectCount(wrapper) > 0) {
                    return Result.error("分类名称已存在");
                }

                category.setId(id);
                category.setUpdateTime(LocalDateTime.now());
                categoryMapper.updateById(category);
                return Result.success("分类更新成功");
            } catch (Exception e) {
                return Result.error("更新失败：" + e.getMessage());
            }
        }

        /**
         * 删除分类
         */
        @DeleteMapping("/categories/{id}")
        public Result<String> deleteCategory(@PathVariable Long id) {
            try {
                // 检查分类下是否有文章
                LambdaQueryWrapper<Article> articleWrapper = new LambdaQueryWrapper<>();
                Category category = categoryMapper.selectById(id);
                if (category != null) {
                    articleWrapper.eq(Article::getCategory, category.getName());
                    long articleCount = articleMapper.selectCount(articleWrapper);
                    if (articleCount > 0) {
                        return Result.error("该分类下还有文章，无法删除");
                    }
                }

                categoryMapper.deleteById(id);
                return Result.success("分类删除成功");
            } catch (Exception e) {
                return Result.error("删除失败：" + e.getMessage());
            }
        }

        /**
         * 切换分类状态
         */
        @PostMapping("/categories/{id}/toggle")
        public Result<String> toggleCategoryStatus(@PathVariable Long id) {
            try {
                Category category = categoryMapper.selectById(id);
                if (category == null) {
                    return Result.error("分类不存在");
                }

                category.setIsActive(!category.getIsActive());
                category.setUpdateTime(LocalDateTime.now());
                categoryMapper.updateById(category);

                return Result.success("状态切换成功");
            } catch (Exception e) {
                return Result.error("操作失败：" + e.getMessage());
            }
        }

        /**
         * 获取所有标签
         */
        @GetMapping("/tags")
        public Result<List<Tag>> getTags() {
            List<Tag> tags = tagMapper.selectList(new LambdaQueryWrapper<Tag>()
                    .orderByDesc(Tag::getUsageCount));
            return Result.success(tags);
        }

        /**
         * 创建标签
         */
        @PostMapping("/tags")
        public Result<String> createTag(@RequestBody Tag tag) {
            try {
                // 检查标签是否已存在
                LambdaQueryWrapper<Tag> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Tag::getName, tag.getName());
                if (tagMapper.selectCount(wrapper) > 0) {
                    return Result.error("标签已存在");
                }

                tag.setCreateTime(LocalDateTime.now());
                tag.setUsageCount(0L);
                tagMapper.insert(tag);
                return Result.success("标签创建成功");
            } catch (Exception e) {
                return Result.error("创建失败：" + e.getMessage());
            }
        }

        /**
         * 删除标签
         */
        @DeleteMapping("/tags/{id}")
        public Result<String> deleteTag(@PathVariable Long id) {
            try {
                tagMapper.deleteById(id);
                return Result.success("标签删除成功");
            } catch (Exception e) {
                return Result.error("删除失败：" + e.getMessage());
            }
        }

        /**
         * 发布文章
         */
        @PostMapping("/articles/{id}/publish")
        public Result<String> publishArticle(@PathVariable String id) {
            try {
                Article article = articleMapper.selectById(id);
                if (article == null) {
                    return Result.error("文章不存在");
                }
                article.setStatus(1); // 发布状态
                article.setUpdateTime(LocalDateTime.now());
                articleMapper.updateById(article);
                return Result.success("文章发布成功");
            } catch (Exception e) {
                return Result.error("发布失败：" + e.getMessage());
            }
        }

        /**
         * 撤回文章
         */
        @PostMapping("/articles/{id}/withdraw")
        public Result<String> withdrawArticle(@PathVariable String id) {
            try {
                Article article = articleMapper.selectById(id);
                if (article == null) {
                    return Result.error("文章不存在");
                }
                article.setStatus(0); // 草稿状态
                article.setUpdateTime(LocalDateTime.now());
                articleMapper.updateById(article);
                return Result.success("文章撤回成功");
            } catch (Exception e) {
                return Result.error("撤回失败：" + e.getMessage());
            }
        }

    /**
     * 增加文章浏览量
     */
    @PostMapping("/articles/{id}/view")
    public Result<String> increaseViewCount(@PathVariable String id) {
        try {
            Article article = articleMapper.selectById(id);
            if (article == null) {
                return Result.error("文章不存在");
            }

            // 增加浏览量
            article.setViewCount(article.getViewCount() + 1);
            articleMapper.updateById(article);

            return Result.success("浏览量更新成功");
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 批量增加文章浏览量
     */
    @PostMapping("/articles/batch-view")
    public Result<String> batchIncreaseViewCount(@RequestBody ArticleViewController.BatchViewRequest request) {
        try {
            for (String articleId : request.getArticleIds()) {
                Article article = articleMapper.selectById(articleId);
                if (article != null) {
                    article.setViewCount(article.getViewCount() + 1);
                    articleMapper.updateById(article);
                }
            }
            return Result.success("批量更新成功");
        } catch (Exception e) {
            return Result.error("批量更新失败：" + e.getMessage());
        }
    }

        /**
         * 清理旧新闻
         */
        @PostMapping("/clear-old")
        public Result<String> clearOldNews() {
            try {
                LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);

                // 删除30天前的新闻
                LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
                wrapper.lt(Article::getCreateTime, thirtyDaysAgo);

                int deletedCount = articleMapper.delete(wrapper);

                return Result.success("已清理 " + deletedCount + " 条旧新闻");
            } catch (Exception e) {
                return Result.error("清理失败: " + e.getMessage());
            }
        }

        // 权重设置请求类
        @Setter
        @Getter
        public static class WeightRequest {
            // getters and setters
            private String articleId;
            private String weightType; // top, hot, recommend
            private Integer orderValue;

        }
    }